"""
模板库页面

管理和浏览模板的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox
from pathlib import Path
import sys
import asyncio
from typing import List, Dict, Any

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.core.di import injector
from src.repositories.jianying_template_repository import JianyingTemplateRepository


class TemplateLibraryPage(BasePage):
    """模板库页面"""

    def __init__(self, parent, app=None):
        super().__init__(parent, app)
        # 获取数据库仓库
        try:
            self.template_repo = injector.get(JianyingTemplateRepository)
        except Exception as e:
            print(f"警告: 无法获取模板仓库: {e}")
            self.template_repo = None

    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 配置按钮样式
        style = ttk.Style()
        style.configure('Primary.TButton',
                       font=('Arial', 9, 'bold'),
                       padding=(12, 6),
                       foreground='white')
        style.configure('Secondary.TButton',
                       font=('Arial', 9),
                       padding=(10, 5),
                       relief='flat')
        style.configure('Action.TButton',
                       font=('Arial', 9),
                       padding=(8, 4),
                       relief='raised')

        # 配置按钮颜色（如果主题支持）
        try:
            style.map('Primary.TButton',
                     background=[('active', '#0078d4'), ('!active', '#106ebe')],
                     foreground=[('active', 'white'), ('!active', 'white')])
            style.map('Secondary.TButton',
                     background=[('active', '#f3f2f1'), ('!active', '#faf9f8')],
                     foreground=[('active', '#323130'), ('!active', '#605e5c')])
            style.map('Action.TButton',
                     background=[('active', '#e1dfdd'), ('!active', '#edebe9')])
        except:
            pass  # 如果主题不支持颜色配置，忽略错误

        # 页面标题
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, 20))

        title_label = ttk.Label(
            header_frame,
            text="🎨 模板库",
            style='Title.TLabel'
        )
        title_label.pack(side="left")
        
        # 工具栏
        toolbar_frame = ttk.Frame(self.frame)
        toolbar_frame.pack(fill="x", pady=(0, 20))

        # 主要操作按钮组
        main_buttons_frame = ttk.LabelFrame(toolbar_frame, text="模板操作", padding="8")
        main_buttons_frame.pack(side="left", padx=(0, 15))

        ttk.Button(
            main_buttons_frame,
            text="📥 单个导入",
            command=self.import_template,
            style='Primary.TButton'
        ).pack(side="left", padx=(0, 8))

        ttk.Button(
            main_buttons_frame,
            text="📦 批量导入",
            command=self.batch_import_templates,
            style='Secondary.TButton'
        ).pack(side="left", padx=(0, 8))

        ttk.Button(
            main_buttons_frame,
            text="🔄 刷新列表",
            command=self.refresh_templates,
            style='Action.TButton'
        ).pack(side="left")

        # 批量管理按钮组
        batch_buttons_frame = ttk.LabelFrame(toolbar_frame, text="批量管理", padding="8")
        batch_buttons_frame.pack(side="left", padx=(0, 15))

        ttk.Button(
            batch_buttons_frame,
            text="✅ 启用选中",
            command=self.enable_selected_templates,
            style='Action.TButton'
        ).pack(side="left", padx=(0, 8))

        ttk.Button(
            batch_buttons_frame,
            text="❌ 禁用选中",
            command=self.disable_selected_templates,
            style='Action.TButton'
        ).pack(side="left")

        # 搜索和过滤区域
        search_filter_frame = ttk.LabelFrame(toolbar_frame, text="搜索与过滤", padding="8")
        search_filter_frame.pack(side="left", padx=(0, 15))

        # 搜索框
        search_container = ttk.Frame(search_filter_frame)
        search_container.pack(side="left", padx=(0, 15))

        ttk.Label(search_container, text="🔍", font=('Arial', 10)).pack(side="left", padx=(0, 3))

        self.search_var = tk.StringVar()
        self.search_var.trace('w', self.on_search_changed)
        search_entry = ttk.Entry(search_container, textvariable=self.search_var, width=18, font=('Arial', 9))
        search_entry.pack(side="left")

        # 过滤选项
        filter_container = ttk.Frame(search_filter_frame)
        filter_container.pack(side="left")

        ttk.Label(filter_container, text="📐", font=('Arial', 10)).pack(side="left", padx=(0, 3))

        self.canvas_ratio_var = tk.StringVar(value="全部")
        canvas_ratio_combo = ttk.Combobox(
            filter_container,
            textvariable=self.canvas_ratio_var,
            values=["全部", "16:9", "9:16", "1:1", "4:3"],
            state="readonly",
            width=10
        )
        canvas_ratio_combo.pack(side="left")
        canvas_ratio_combo.bind('<<ComboboxSelected>>', self.on_filter_changed)

        # 状态栏（显示模板总数）
        status_frame = ttk.Frame(self.frame)
        status_frame.pack(fill="x", pady=(0, 10))

        self.status_label = ttk.Label(
            status_frame,
            text="正在加载模板...",
            foreground="blue"
        )
        self.status_label.pack(side="left")

        # 选择状态显示
        self.selection_label = ttk.Label(
            status_frame,
            text="",
            foreground="green"
        )
        self.selection_label.pack(side="right")

        # 模板列表
        list_frame = ttk.LabelFrame(self.frame, text="模板列表", padding="10")
        list_frame.pack(fill="both", expand=True)
        
        # 创建模板列表
        columns = ('name', 'type', 'duration', 'canvas', 'segments', 'status')
        self.template_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=12)
        
        # 设置列标题
        headers = {
            'name': '模板名称',
            'type': '类型',
            'duration': '时长',
            'canvas': '画布',
            'segments': '片段数',
            'status': '状态'
        }
        
        for col, title in headers.items():
            self.template_tree.heading(col, text=title)
            self.template_tree.column(col, width=120)

        # 绑定选择事件
        self.template_tree.bind('<<TreeviewSelect>>', self.on_template_selection_changed)

        # 滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.template_tree.yview)
        self.template_tree.configure(yscrollcommand=scrollbar.set)

        # 布局
        self.template_tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 加载模板数据
        self.load_templates_from_database()

    def load_templates_from_database(self):
        """从数据库加载模板数据"""
        try:
            if not self.template_repo:
                return

            # 从数据库获取所有模板
            templates = self.template_repo.get_all()

            # 清空现有数据
            for item in self.template_tree.get_children():
                self.template_tree.delete(item)

            if not templates:
                # 如果数据库中没有模板，显示提示信息
                self.template_tree.insert('', 'end', values=(
                    "暂无模板数据", "请导入模板", "-", "-", "-", "空"
                ))
                self.update_status_display(0, 0)
                return

            # 添加模板数据到树形控件
            for template in templates:
                # 格式化时长
                duration_str = self.format_duration(template.duration_seconds)

                # 格式化画布比例
                canvas_ratio = template.canvas_ratio or "未知"

                # 格式化片段数
                segments_count = str(template.video_segments_count or 0)

                # 确定状态（考虑启用/禁用状态）
                if not getattr(template, 'is_enabled', True):
                    status = "已禁用"
                elif not template.template_path:
                    status = "路径缺失"
                else:
                    status = "可用"

                # 插入数据
                self.template_tree.insert('', 'end', values=(
                    template.template_name or "未命名模板",
                    "剪映",  # 类型固定为剪映
                    duration_str,
                    canvas_ratio,
                    segments_count,
                    status
                ))

            # 更新状态显示
            enabled_count = len([t for t in templates if getattr(t, 'is_enabled', True)])
            self.update_status_display(len(templates), enabled_count)

        except Exception as e:
            print(f"从数据库加载模板失败: {e}")

    def format_duration(self, duration_seconds):
        """格式化时长显示"""
        if not duration_seconds:
            return "00:00"

        minutes = int(duration_seconds // 60)
        seconds = int(duration_seconds % 60)
        return f"{minutes:02d}:{seconds:02d}"


    def import_template(self):
        """导入模板"""
        from tkinter import filedialog, messagebox

        # 选择模板目录
        template_dir = filedialog.askdirectory(
            title="选择剪映模板目录",
            initialdir=str(Path("dist/剪映模板"))  # 默认指向测试目录
        )

        if template_dir:
            try:
                # 显示导入确认对话框
                template_path = Path(template_dir)
                confirm_msg = f"确定要导入模板吗？\n\n模板路径: {template_path}\n模板名称: {template_path.name}"

                if not messagebox.askyesno("确认导入", confirm_msg):
                    return

                # 显示进度提示
                progress_window = self.show_import_progress("正在导入模板...")

                # 调用模板扫描服务
                from src.services.jianying_template_scanner import JianyingTemplateScanner
                scanner = injector.get(JianyingTemplateScanner)

                # 扫描单个模板目录
                result = self.import_single_template(scanner, template_dir)

                # 关闭进度窗口
                progress_window.destroy()

                # 显示导入结果
                self.show_import_result(result, template_path.name)

                # 刷新模板列表
                self.load_templates_from_database()

            except Exception as e:
                if 'progress_window' in locals():
                    progress_window.destroy()
                messagebox.showerror("错误", f"导入模板失败: {e}")
                import traceback
                print(f"导入模板详细错误: {traceback.format_exc()}")

    def refresh_templates(self):
        """刷新模板列表"""
        try:
            self.load_templates_from_database()
            tk.messagebox.showinfo("提示", "模板列表已刷新")
        except Exception as e:
            tk.messagebox.showerror("错误", f"刷新模板列表失败: {e}")

    def get_template_statistics(self):
        """获取模板统计信息"""
        if not self.template_repo:
            return {
                'total_templates': 0,
                'total_video_segments': 0,
                'latest_scan': None
            }

        try:
            return self.template_repo.get_statistics()
        except Exception as e:
            print(f"获取模板统计信息失败: {e}")
            return {
                'total_templates': 0,
                'total_video_segments': 0,
                'latest_scan': None
            }

    def on_search_changed(self, *args):
        """搜索内容变化时的回调"""
        self.filter_templates()

    def on_filter_changed(self, event=None):
        """过滤条件变化时的回调"""
        self.filter_templates()

    def filter_templates(self):
        """根据搜索和过滤条件显示模板"""
        search_text = self.search_var.get().lower()
        canvas_ratio = self.canvas_ratio_var.get()

        # 重新加载所有数据
        self.load_templates_from_database()

        # 如果没有搜索条件，直接返回
        if not search_text and canvas_ratio == "全部":
            return

        # 获取所有项目
        all_items = self.template_tree.get_children()
        items_to_hide = []

        for item in all_items:
            values = self.template_tree.item(item)['values']
            if not values:
                continue

            name = str(values[0]).lower()
            item_canvas_ratio = str(values[3])

            # 检查搜索条件
            search_match = not search_text or search_text in name

            # 检查画布比例过滤
            ratio_match = canvas_ratio == "全部" or canvas_ratio == item_canvas_ratio

            # 如果不匹配，标记为隐藏
            if not (search_match and ratio_match):
                items_to_hide.append(item)

        # 删除不匹配的项目
        for item in items_to_hide:
            self.template_tree.delete(item)

    def import_single_template(self, scanner, template_dir):
        """导入单个模板"""
        try:
            # 检查是否是有效的模板目录
            template_path = Path(template_dir)

            # 检查必要的文件
            required_files = ["draft_content.json", "draft_meta_info.json"]
            missing_files = []

            for file_name in required_files:
                if not (template_path / file_name).exists():
                    missing_files.append(file_name)

            if missing_files:
                raise ValueError(f"模板目录缺少必要文件: {', '.join(missing_files)}")

            # 使用扫描器处理单个模板
            result = scanner._process_single_template(template_path, force_update=True)

            return {
                "success": True,
                "template_id": result["template_id"],
                "action": result["action"],
                "video_segments_count": result.get("video_segments_count", 0),
                "message": f"模板 '{result['template_id']}' 导入成功"
            }

        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"导入失败: {e}"
            }

    def show_import_progress(self, message):
        """显示导入进度窗口"""
        progress_window = tk.Toplevel(self.parent)
        progress_window.title("导入进度")
        progress_window.geometry("400x150")
        progress_window.resizable(False, False)

        # 居中显示
        progress_window.transient(self.parent)
        progress_window.grab_set()

        # 内容
        frame = ttk.Frame(progress_window, padding="20")
        frame.pack(fill="both", expand=True)

        # 图标和消息
        icon_label = ttk.Label(frame, text="📥", font=("Arial", 24))
        icon_label.pack(pady=(0, 10))

        message_label = ttk.Label(frame, text=message, font=("Arial", 12))
        message_label.pack(pady=(0, 10))

        # 进度条
        progress_bar = ttk.Progressbar(frame, mode='indeterminate')
        progress_bar.pack(fill="x", pady=(0, 10))
        progress_bar.start()

        # 更新界面
        progress_window.update()

        return progress_window

    def show_import_result(self, result, template_name):
        """显示导入结果"""
        from tkinter import messagebox

        if result["success"]:
            action_text = "更新" if result["action"] == "updated" else "创建"
            segments_count = result.get("video_segments_count", 0)

            success_msg = f"✅ 模板导入成功！\n\n"
            success_msg += f"模板名称: {template_name}\n"
            success_msg += f"操作类型: {action_text}\n"
            success_msg += f"视频片段数: {segments_count}个\n"
            success_msg += f"模板ID: {result['template_id']}"

            messagebox.showinfo("导入成功", success_msg)
        else:
            error_msg = f"❌ 模板导入失败！\n\n"
            error_msg += f"模板名称: {template_name}\n"
            error_msg += f"错误信息: {result['error']}"

            messagebox.showerror("导入失败", error_msg)

    def batch_import_templates(self):
        """批量导入模板"""
        from tkinter import filedialog, messagebox

        # 选择模板根目录
        template_root_dir = filedialog.askdirectory(
            title="选择包含多个模板的根目录",
            initialdir=str(Path("dist/剪映模板"))
        )

        if not template_root_dir:
            return

        template_root_path = Path(template_root_dir)

        # 扫描子目录，查找模板
        template_dirs = []
        for item in template_root_path.iterdir():
            if item.is_dir():
                # 检查是否包含必要的模板文件
                if (item / "draft_content.json").exists():
                    template_dirs.append(item)

        if not template_dirs:
            messagebox.showwarning("警告", f"在目录 {template_root_path} 中未找到有效的模板目录")
            return

        # 确认批量导入
        confirm_msg = f"找到 {len(template_dirs)} 个模板目录，确定要批量导入吗？\n\n"
        confirm_msg += "模板列表:\n"
        for i, template_dir in enumerate(template_dirs[:5], 1):
            confirm_msg += f"{i}. {template_dir.name}\n"
        if len(template_dirs) > 5:
            confirm_msg += f"... 还有 {len(template_dirs) - 5} 个模板"

        if not messagebox.askyesno("确认批量导入", confirm_msg):
            return

        # 显示进度窗口
        progress_window = self.show_batch_import_progress(len(template_dirs))

        try:
            from src.services.jianying_template_scanner import JianyingTemplateScanner
            scanner = injector.get(JianyingTemplateScanner)

            success_count = 0
            error_count = 0
            results = []

            for i, template_dir in enumerate(template_dirs):
                # 更新进度
                self.update_batch_progress(progress_window, i + 1, len(template_dirs), template_dir.name)

                try:
                    result = self.import_single_template(scanner, str(template_dir))
                    if result["success"]:
                        success_count += 1
                    else:
                        error_count += 1
                    results.append((template_dir.name, result))
                except Exception as e:
                    error_count += 1
                    results.append((template_dir.name, {"success": False, "error": str(e)}))

            # 关闭进度窗口
            progress_window.destroy()

            # 显示批量导入结果
            self.show_batch_import_result(success_count, error_count, results)

            # 刷新模板列表
            self.load_templates_from_database()

        except Exception as e:
            progress_window.destroy()
            messagebox.showerror("错误", f"批量导入失败: {e}")

    def show_batch_import_progress(self, total_count):
        """显示批量导入进度窗口"""
        progress_window = tk.Toplevel(self.parent)
        progress_window.title("批量导入进度")
        progress_window.geometry("500x200")
        progress_window.resizable(False, False)

        # 居中显示
        progress_window.transient(self.parent)
        progress_window.grab_set()

        # 内容
        frame = ttk.Frame(progress_window, padding="20")
        frame.pack(fill="both", expand=True)

        # 标题
        title_label = ttk.Label(frame, text="📦 批量导入模板", font=("Arial", 14, "bold"))
        title_label.pack(pady=(0, 15))

        # 当前处理的模板
        progress_window.current_label = ttk.Label(frame, text="准备开始...", font=("Arial", 10))
        progress_window.current_label.pack(pady=(0, 10))

        # 进度条
        progress_window.progress_var = tk.DoubleVar()
        progress_bar = ttk.Progressbar(
            frame,
            variable=progress_window.progress_var,
            maximum=total_count,
            length=400
        )
        progress_bar.pack(fill="x", pady=(0, 10))

        # 进度文本
        progress_window.progress_text = ttk.Label(frame, text=f"0 / {total_count}")
        progress_window.progress_text.pack()

        # 更新界面
        progress_window.update()

        return progress_window

    def update_batch_progress(self, progress_window, current, total, template_name):
        """更新批量导入进度"""
        try:
            progress_window.current_label.config(text=f"正在处理: {template_name}")
            progress_window.progress_var.set(current)
            progress_window.progress_text.config(text=f"{current} / {total}")
            progress_window.update()
        except:
            pass  # 窗口可能已关闭

    def show_batch_import_result(self, success_count, error_count, results):
        """显示批量导入结果"""
        total_count = success_count + error_count

        result_msg = f"📊 批量导入完成！\n\n"
        result_msg += f"总计: {total_count} 个模板\n"
        result_msg += f"成功: {success_count} 个\n"
        result_msg += f"失败: {error_count} 个\n"
        result_msg += f"成功率: {success_count / total_count * 100:.1f}%\n\n"

        if error_count > 0:
            result_msg += "失败的模板:\n"
            for template_name, result in results:
                if not result["success"]:
                    result_msg += f"• {template_name}: {result.get('error', '未知错误')}\n"

        if error_count == 0:
            messagebox.showinfo("批量导入成功", result_msg)
        else:
            messagebox.showwarning("批量导入完成", result_msg)

    def enable_selected_templates(self):
        """启用选中的模板"""
        selected_items = self.template_tree.selection()

        if not selected_items:
            messagebox.showwarning("警告", "请先选择要启用的模板")
            return

        # 获取选中的模板名称
        template_names = []
        for item in selected_items:
            values = self.template_tree.item(item)['values']
            if values and len(values) > 0:
                template_names.append(values[0])

        if not template_names:
            return

        # 确认操作
        confirm_msg = f"确定要启用以下 {len(template_names)} 个模板吗？\n\n"
        for name in template_names[:5]:
            confirm_msg += f"• {name}\n"
        if len(template_names) > 5:
            confirm_msg += f"... 还有 {len(template_names) - 5} 个模板"

        if not messagebox.askyesno("确认启用", confirm_msg):
            return

        # 执行启用操作
        try:
            success_count = 0
            for template_name in template_names:
                # 更新数据库中的 is_enabled 字段
                template = self.template_repo.get_by_template_id(template_name)
                if template:
                    self.template_repo.update(template.id, is_enabled=True)
                    success_count += 1

            messagebox.showinfo("操作成功", f"已成功启用 {success_count} 个模板")
            self.load_templates_from_database()

        except Exception as e:
            messagebox.showerror("错误", f"启用模板失败: {e}")
            import traceback
            print(f"启用模板详细错误: {traceback.format_exc()}")

    def disable_selected_templates(self):
        """禁用选中的模板"""
        selected_items = self.template_tree.selection()

        if not selected_items:
            messagebox.showwarning("警告", "请先选择要禁用的模板")
            return

        # 获取选中的模板名称
        template_names = []
        for item in selected_items:
            values = self.template_tree.item(item)['values']
            if values and len(values) > 0:
                template_names.append(values[0])

        if not template_names:
            return

        # 确认操作
        confirm_msg = f"确定要禁用以下 {len(template_names)} 个模板吗？\n\n"
        confirm_msg += "禁用后这些模板将不会在模板选择中显示。\n\n"
        for name in template_names[:5]:
            confirm_msg += f"• {name}\n"
        if len(template_names) > 5:
            confirm_msg += f"... 还有 {len(template_names) - 5} 个模板"

        if not messagebox.askyesno("确认禁用", confirm_msg):
            return

        # 执行禁用操作
        try:
            success_count = 0
            for template_name in template_names:
                # 更新数据库中的 is_enabled 字段
                template = self.template_repo.get_by_template_id(template_name)
                if template:
                    self.template_repo.update(template.id, is_enabled=False)
                    success_count += 1

            messagebox.showinfo("操作成功", f"已成功禁用 {success_count} 个模板")
            self.load_templates_from_database()

        except Exception as e:
            messagebox.showerror("错误", f"禁用模板失败: {e}")
            import traceback
            print(f"禁用模板详细错误: {traceback.format_exc()}")

    def on_template_selection_changed(self, event):
        """模板选择变化时的回调"""
        selected_items = self.template_tree.selection()
        self.update_selection_display(len(selected_items))

    def update_status_display(self, total_count, enabled_count):
        """更新状态显示"""
        if total_count == 0:
            status_text = "暂无模板数据"
        else:
            disabled_count = total_count - enabled_count
            if disabled_count > 0:
                status_text = f"模板总数: {total_count} 个 (启用: {enabled_count}, 禁用: {disabled_count})"
            else:
                status_text = f"模板总数: {total_count} 个"

        self.status_label.config(text=status_text)

    def update_selection_display(self, selected_count):
        """更新选择状态显示"""
        if selected_count == 0:
            self.selection_label.config(text="")
        elif selected_count == 1:
            self.selection_label.config(text="已选择 1 个模板")
        else:
            self.selection_label.config(text=f"已选择 {selected_count} 个模板")
